/**
 *	Handles game logic requests
 *
 *	temp: also contains temporary ruleset
 *
 *	note: much commonality between validator and winchecker. some kind 
 *	of polymorphic inheritence? class builder?
*/

"use strict"

var GameLogic = {
	
	/**
		@param {Object} game Holds the state of the game
		@param {Object} move Holds move.x, move.y, movement co-ordinates for proposed move
		@returns {Boolean} Returns true on success
		@throws {string} Error message
	*/
	validate: function(game, move) {
		var v = new this._validator(game, move),
			valid = false
		
		valid &= v.checkGameAlreadyWon()
		valid &= v.checkSquareAlreadyFilled()
		
		return ( valid ? true : false )			//parse to bool
	},
		
	_validator: function(game, move) {
		if (this === GameLogic)  throw "incorrect constructor call"

		this.game = game
		this.move = move
	},
	
	checkWin: function(game) {
		var result, w = new this._winChecker(game)
		var ruleorder = [									//make sure rules are appraised in order
			"checkAllSquaresFull"
		]
		
		for (var i=0, ii=ruleorder.length; i<ii; i++) {		//loop through all rules and check for a winner
				result = w[ ruleorder[i] ]()				//run the rule
				if (result !== 0)  return result			//return a winner is found
		}
		
		return 0											//no winner, return 0 (game in progress)
	},
	
	_winChecker: function(game) {
		if (this === GameLogic)  throw "incorrect constructor call"
		
		this.game = game
	}
}


GameLogic._validator.prototype = {

	checkGameAlreadyWon: function() {
		if (this.game.winner !== 0) {
			return false
		}
		return true
	},

	checkSquareAlreadyFilled: function() {
		var y = this.move.y, x = this.move.x
		if (this.game.state[y][x] !== 0) {
			throw "square already occupied"
		}
		return true
	},
	
}


GameLogic._winChecker.prototype = {
	
	checkAllSquaresFull: function() {
		var state = this.game.state
		for (var y=0, yy=state.length; y<yy; y++) {
			for (var x=0, xx=state[0].length; x<xx; x++) {
				 if (state[y][x] == 0)  return false
			}
		}
		return -1					//-1 signifies a draw
	}
	
}